package com.smasher.update.component.download

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.smasher.update.R

class DownloadHelper(context: Context) {

    private val packageManager: PackageManager = context.packageManager
    private val packageName: String = context.packageName // 或者直接写应用的包名字符串
    private val notificationManager: NotificationManager

    val versionCode: Long

    init {
        versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            queryVersionCode()
        } else {
            queryVersionCodeLow()
        }
        notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        createProgressNotificationChannel()
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun queryVersionCode(): Long {
        var versionCode: Long = 0L

        try {
            val flag = PackageManager.GET_META_DATA.toLong()
            val packageInfo =
                packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flag))
            versionCode = packageInfo.longVersionCode // 如果获取失败，返回0作为默认值
        } catch (e: PackageManager.NameNotFoundException) {
            versionCode = 0L
            Log.e(TAG, "AppVersion Failed to retrieve version code", e)
        }
        return versionCode
    }

    private fun queryVersionCodeLow(): Long {
        var versionCode: Int = 0

        try {
            val flag = PackageManager.GET_META_DATA.toLong()
            val packageInfo =
                packageManager.getPackageInfo(packageName, PackageManager.GET_META_DATA)
            versionCode = packageInfo.versionCode // 如果获取失败，返回0作为默认值
        } catch (e: PackageManager.NameNotFoundException) {
            versionCode = 0
            Log.e(TAG, "AppVersion Failed to retrieve version code", e)
        }

        return versionCode.toLong()
    }

    private fun createProgressNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val list = notificationManager.notificationChannels
            list.forEach { if (it.id == CHANNEL_ID) return }
            val name: CharSequence = "下载更新"
            val description = "版本更新下载进度通知"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, name, importance)
            channel.description = description
            notificationManager.createNotificationChannel(channel)
        }
    }


    fun createNotificationProgress(
        context: Context,
        progress: Int,
        content: String
    ) {
        val builder: NotificationCompat.Builder =
            NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.drawable.notification_update_apk)
                .setContentTitle("版本更新")
                .setContentText(content)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setProgress(100, progress, false)
        notificationManager.notify(NOTIFICATION_UPDATE_APK_ID, builder.build())
    }


    fun cancelNotification() {
        notificationManager.cancel(NOTIFICATION_UPDATE_APK_ID)
    }


    companion object {
        const val TAG = "DownloadImpl"
        const val CHANNEL_ID = "download_apk"
        const val NOTIFICATION_UPDATE_APK_ID = 65534
    }

}